package ext.tianma.project2.APQP.service;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.rmi.RemoteException;
import java.sql.Blob;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Vector;

import org.apache.commons.lang.StringUtils;
import org.dom4j.DocumentException;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.remoting.support.RemoteAccessor;
import org.springframework.stereotype.Service;

import wt.fc.ObjectReference;
import wt.fc.PersistenceHelper;
import wt.fc.QueryResult;
import wt.fc.collections.WTCollection;
import wt.fc.collections.WTHashSet;
import wt.inf.team.ContainerTeamManagedInfo;
import wt.inf.team.ContainerTeamManagedState;
import wt.lifecycle.LifeCycleHelper;
import wt.lifecycle.LifeCycleTemplate;
import wt.method.RemoteMethodServer;
import wt.org.OrganizationServicesHelper;
import wt.org.WTGroup;
import wt.org.WTPrincipal;
import wt.org.WTPrincipalReference;
import wt.org.WTUser;
import wt.projmgmt.admin.Project2;
import wt.query.ClassAttribute;
import wt.query.OrderBy;
import wt.query.QuerySpec;
import wt.query.SearchCondition;
import wt.session.SessionHelper;
import wt.session.SessionServerHelper;
import wt.util.WTException;
import wt.util.WTPropertyVetoException;
import wt.workflow.definer.WfAssignedActivityTemplate;
import wt.workflow.definer.WfProcessTemplate;
import wt.workflow.engine.ProcessData;
import wt.workflow.engine.WfActivity;
import wt.workflow.engine.WfEngineHelper;
import wt.workflow.engine.WfEngineServerHelper;
import wt.workflow.engine.WfEventHelper;
import wt.workflow.engine.WfProcess;
import wt.workflow.engine.WfVotingEventAudit;
import wt.workflow.work.WfAssignedActivity;
import wt.workflow.work.WfAssignment;
import wt.workflow.work.WorkItem;
import wt.workflow.work.WorkflowHelper;

import com.ptc.projectmanagement.plan.Plan;
import com.ptc.projectmanagement.plan.PlanActivity;
import com.ptc.projectmanagement.plan.PlanHelper;
import com.ptc.projectmanagement.plan.PlannableState;

import ext.tianma.model.FormDataXml;
import ext.tianma.project2.APQP.constants.APQPProjectConstant;
import ext.tianma.project2.util.ProjectUtil;
import ext.tianma.util.TMUtil;
import ext.tianma.workflow.BomWorkFlowUtil;
import ext.tianma.workflow.SubmitBomReview;

@Service
public class ProcessService extends RemoteAccessor{
	
	private static final Logger logger = LoggerFactory.getLogger(ProcessService.class);
	
	@Autowired
	APQPProjectService projectservice;
	
	@Autowired
	APQPPlanActivityService planactivityservice;
	
	//流程表单中，活动信息列、项目信息、被驳回的活动   key
	public static final String PROJECTiNFO = "projectInfo";
	public static final String COLUMNS = "columns";
	public static final String REJECTOID = "rejectActivitysInfo";
	public static final String ACTIVITYSINFO = "activitysInfo";
	
	/**
	 * 创建流程
	 * @param processTemplate
	 * @param lifeCycleTemplate
	 * @param project
	 * @throws WTException
	 * @throws WTPropertyVetoException
	 * @author xucr
	 * @CreateDate 2020年8月27日
	 */
	public WfProcess createProcess(String processTemplate, String lifeCycleTemplate ,Project2 project) {
		WfProcess wfprocess = null;
		try {
			//获取流程模板
			WfProcessTemplate wfprocessTemplate = SubmitBomReview.getWfProcessTemplateByName(processTemplate);
			//获取生命周期
			LifeCycleTemplate lifeCycle = LifeCycleHelper.service.getLifeCycleTemplate(lifeCycleTemplate, wt.inf.container.WTContainerHelper.getExchangeRef());
			
			String processName = project.getName() + "报告审批流程";
			WTPrincipalReference wtprincipalreference = WTPrincipalReference.newWTPrincipalReference(project.getOwner());
		
			wfprocess = WfEngineHelper.service.createProcess(wfprocessTemplate, lifeCycle, project.getContainerReference());
			WfEngineServerHelper.service.setPrimaryBusinessObject(wfprocess,project);
			wfprocess.setName(processName);
			ProcessData processdata = wfprocess.getContext();
			wfprocess.setCreator(wtprincipalreference);
			
			wfprocess = (WfProcess)PersistenceHelper.manager.save(wfprocess);	
			wfprocess.start(processdata, true, project.getContainerReference());
		} catch (WTException e) {
			e.printStackTrace();
			logger.error("createProcess >>>catch1 >>>>>: " + e.getLocalizedMessage(Locale.getDefault()));
		} catch (WTPropertyVetoException e) {
			e.printStackTrace();
			logger.error("createProcess >>>catch2 >>>>>: " + e.getLocalizedMessage(Locale.getDefault()));
		}
		return wfprocess;
	}
	
	/**
	 * 完成任务
	 * @param workItemOid
	 * @param comments
	 * @param eventList
	 * @return
	 * @throws WTException
	 * @author xucr
	 * @CreateDate 2020年8月27日
	 */
	@SuppressWarnings("rawtypes")
	public boolean completeTask(String workItemOid, String comments, Vector eventList) throws WTException {
		boolean flag = false;
		try {
			WorkItem workitem = (WorkItem) TMUtil.oid2Obj(workItemOid);
			WTPrincipal currentUser = SessionHelper.manager.getPrincipal();
			WTPrincipalReference currentUserRef = WTPrincipalReference.newWTPrincipalReference(currentUser);

			Locale locale = Locale.getDefault();
			if (workitem == null) {
				String messageTip = "";
				if (locale.equals(Locale.CHINA))
					messageTip = "该任务不再有效，因为它已完成。";
				else {
					messageTip = "Task is not efficiency. Because it has complete .";
				}
				throw new WTException(messageTip);
			}

			boolean isHasAccess = isHasCompleteTaskAccess(workitem, currentUser);
			if (!isHasAccess) {
				String messageTip = "";
				if (locale.equals(Locale.CHINA))
					messageTip = "当前任务属于:" + workitem.getOwnership().getOwner().getName() + "，您无法完成。";
				else {
					messageTip = "Task is belong to:" + workitem.getOwnership().getOwner().getName() + ", you can't finish it. ";
				}
				throw new WTException(messageTip);
			}
			
			SessionServerHelper.manager.setAccessEnforced(false);
			WorkflowHelper.service.workComplete(workitem, currentUserRef, eventList);
			recordeComments(workItemOid, comments, eventList);
			
		} catch (Exception e) {
			logger.error("completeTask >>>catch1 >>>>>: " + e.getLocalizedMessage());
			Object[] param = { "completeTask" };
			throw new WTException(e, "wt.fc.fcResource", "0", param);
		}
		return flag;
	};
	
	/**
	 * 提交审批意见
	 * @param wkitem
	 * @param comments
	 * @param eventList
	 * @throws WTException
	 * @throws WTPropertyVetoException
	 * @author xucr
	 * @CreateDate 2020年8月27日
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public void recordeComments(String workItemOid, String comments, Vector eventList) throws WTException, WTPropertyVetoException {
		if (!RemoteMethodServer.ServerFlag) {
			try {
				Class[] argTypes = { String.class, String.class, Vector.class };
				Object[] args = { workItemOid, comments, eventList };
				RemoteMethodServer.getDefault().invoke("recordeComments", ProcessService.class.getName(), null, argTypes, args);
			} catch (RemoteException rme) {
				Object[] param = { "recordeComments" };
				throw new WTException(rme, "wt.fc.fcResource", "0", param);
			} catch (InvocationTargetException e) {
				e.printStackTrace();
			}
		} else {
			WorkItem workitem = (WorkItem) TMUtil.oid2Obj(workItemOid);
			WTPrincipalReference currentUserRef = WTPrincipalReference.newWTPrincipalReference(SessionHelper.manager.getPrincipal());
			WfAssignedActivity wa = (WfAssignedActivity) ((WfAssignment) workitem.getParentWA().getObject()).getSource().getObject();
			boolean isSigningRequired = ((WfAssignedActivityTemplate) wa.getTemplateReference().getObject()).isSigningRequired();

			int trypCount = wa.getTripCount();

			ArrayList assigneerAudit = new ArrayList();
			QueryResult result = getVotingEventsForActivity(wa, true, true);
			while (result.hasMoreElements()) {
				WfVotingEventAudit audit = (WfVotingEventAudit) result.nextElement();
				if ((workitem.getRole().equals(audit.getRole())) && (currentUserRef.equals(audit.getAssigneeRef()))) {
					assigneerAudit.add(audit);
				}
			}
			SessionServerHelper.manager.setAccessEnforced(false);
			if (trypCount > assigneerAudit.size()) {
				WfEventHelper.createVotingEvent(null, wa, workitem,currentUserRef, comments, eventList,isSigningRequired, workitem.isRequired());
			} else {
				WfVotingEventAudit audit = null;
				for (int i = 0; i < assigneerAudit.size(); i++) {
					if (audit == null)
						audit = (WfVotingEventAudit) assigneerAudit.get(i);
					else if (audit.getCreateTimestamp().before(((WfVotingEventAudit) assigneerAudit.get(i)).getCreateTimestamp())) {
						audit = (WfVotingEventAudit) assigneerAudit.get(i);
					}
				}
				if (audit != null) {
					audit.setUserComment(comments);
					PersistenceHelper.manager.save(audit);
				}
			}
			SessionServerHelper.manager.setAccessEnforced(true);
		}
	}
	
	/**
	 * 获取活动路由
	 * 
	 * @param activity
	 * @param isAll 是否最新
	 * @param order 是否排序
	 * @return
	 * @throws WTException
	 * @throws WTPropertyVetoException
	 * @author xucr
	 * @CreateDate 2020年8月27日
	 */
	public QueryResult getVotingEventsForActivity(
			WfAssignedActivity activity, boolean isAll, boolean order)
			throws WTException, WTPropertyVetoException {
		logger.debug("getVotingEventsForActivity():activity=" + activity + " isAll=" + isAll);
		QuerySpec qs = new QuerySpec();
		int votingIndex = qs.appendClassList(WfVotingEventAudit.class, true);
		int activityIndex = qs.appendClassList(WfAssignedActivity.class, false);
		qs.appendWhere(new SearchCondition(new ClassAttribute(WfVotingEventAudit.class, "activityKey"), 
				SearchCondition.EQUAL, new ClassAttribute(WfAssignedActivity.class, "key")), new int[] { votingIndex, activityIndex });

		if (activity != null) {
			if (!isAll) {
				qs.appendAnd();
				int tripCount = activity.getTripCount();
				qs.appendWhere(new SearchCondition(WfVotingEventAudit.class, "tripCount", "=", tripCount), new int[] { votingIndex });
			}
			qs.appendAnd();
			long id = activity.getPersistInfo().getObjectIdentifier().getId();
			qs.appendWhere(new SearchCondition(WfActivity.class, "thePersistInfo.theObjectIdentifier.id", "=", id), new int[] { activityIndex });
		}
		qs.setQuerySet(false);
		OrderBy orderBy = new OrderBy(new ClassAttribute(WfVotingEventAudit.class, "thePersistInfo.updateStamp"), order);
		qs.appendOrderBy(orderBy, new int[] { votingIndex });
		QueryResult qr = PersistenceHelper.manager.find(qs);
		logger.debug("getVotingEventsForActivity():qr.size()=" + qr.size());
		return qr;
	}
	
	/**
	 * 判断当前人是否对当前活动有完成权限
	 * @param workitem
	 * @param currentUser
	 * @return
	 * @author xucr
	 * @CreateDate 2020年8月27日
	 */
	public boolean isHasCompleteTaskAccess(WorkItem workitem, WTPrincipal currentUser) {
		try {
			if (workitem != null) {
				WTPrincipal workitemOwner = workitem.getOwnership().getOwner().getPrincipal();
				WTGroup group = OrganizationServicesHelper.manager.getGroup("Administrators");
				if ((workitemOwner.equals(currentUser)) || (group.isMember(currentUser)))
					return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return false;
	};
	
	/**
	 * 设置表单数据
	 * @param process
	 * @param project
	 * @throws WTException
	 * @author xucr
	 * @CreateDate 2020年8月27日
	 */
	public void setFormDataXml(WfProcess process, Project2 project) throws WTException {
		FormDataXml xml = FormDataXml.newFormDataXml();
		JSONObject obj = new JSONObject();
		try {
			WTUser u = (WTUser) SessionHelper.manager.getPrincipal();
			JSONObject activitysInfo = planactivityservice.getPlanActivityView(project);//初始化流程表单数据时，拿实际项目中的存储
			JSONObject projectInfo = projectservice.findAPQP(project, u, APQPProjectService.READPROJECTTYPE[0]);
			obj.put(COLUMNS, activitysInfo.getJSONArray(COLUMNS));// 表格列
			obj.put(PROJECTiNFO, projectInfo);//项目信息
			obj.put(ACTIVITYSINFO, activitysInfo.getJSONArray("data"));//活动信息
			
			
			xml.setPersistable(ObjectReference.newObjectReference(project));
			xml.setProcess(ObjectReference.newObjectReference(process));
			xml.setFormcontent(ProjectUtil.str2Blob(obj.toString()));
			xml.setStatus(APQPProjectConstant.FORMDATA_STATUS_POTENTIAL);
			
			PersistenceHelper.manager.save(xml);
		} catch (DocumentException | IOException | JSONException e) {
			logger.error("createProcess >>>catch1 >>>>>: " + e.getLocalizedMessage());
			e.printStackTrace();
		} catch (WTPropertyVetoException e) {
			logger.error("createProcess >>>catch2 >>>>>: " + e.getLocalizedMessage());
			e.printStackTrace();
		}
	}
	
	/**
	 * 查询表单信息
	 * @param process
	 * @param project
	 * @throws WTException
	 * @author xucr
	 * @throws JSONException 
	 * @CreateDate 2020年8月27日
	 */
	public JSONObject getFormDataXml(WfProcess process) throws WTException, JSONException {
		FormDataXml xml = findFormDataXml(process, null);
		JSONObject obj = null;
		if(null != process) {
			Blob blob = xml.getFormcontent();
			String str = ProjectUtil.blob2str(blob);
			
			obj = new JSONObject(str);
		} else {
			obj = new JSONObject();
		}
		return obj;
	}
	
	/**
	 * 查询表单信息
	 * @param processOid
	 * @return
	 * @throws WTException
	 * @throws JSONException
	 * @author xucr
	 * @CreateDate 2020年8月27日
	 */
	public JSONObject getFormDataXml(String processOid) throws WTException, JSONException {
		WfProcess process = (WfProcess) TMUtil.oid2Obj(processOid);
		JSONObject obj = getFormDataXml(process);
		return obj;
	}
	
	
	/**
	 * 查询表单信息
	 * @param wfprocess
	 * @param project
	 * @param processState
	 * @return
	 * @throws WTException
	 * @author xucr
	 * @CreateDate 2020年9月16日
	 */
	public FormDataXml findFormDataXml(WfProcess wfprocess, Project2 project) throws WTException {
		/**
		 * 1、根据process只会查询一条数据
		 * 2、根据projcess + formdataxml 进行中的状态，只会查询一条数据
		 * */
		QuerySpec qs = null;
		if(null != wfprocess) {
			qs = ProjectUtil.queryFormDataXml(wfprocess, null, "");
		} else if(null != project) {
			qs = ProjectUtil.queryFormDataXml(null, project, APQPProjectConstant.FORMDATA_STATUS_POTENTIAL);
		}
	    
	    QueryResult qr = PersistenceHelper.manager.find(qs);
	    FormDataXml xml = null;
	    while (qr.hasMoreElements()) {
	    	xml = (FormDataXml) qr.nextElement();
	    }
	    return xml;
	}
	
	/**
	 * 得到APQP的首次流程信息(不分状态)
	 * @param project
	 * @throws WTException
	 * @author xucr
	 * @CreateDate 2020年9月16日
	 */
	public FormDataXml getFirstProcess(Project2 project) throws WTException {
		QuerySpec qs = ProjectUtil.queryFormDataXml(null, project, null);
		QueryResult qr = PersistenceHelper.manager.find(qs);
	    FormDataXml xml = null;
	    while (qr.hasMoreElements()) {
	    	xml = (FormDataXml) qr.nextElement();
	    }
	    return xml;
	}

//	/**
//	 * 资料 : 驳回/取消驳回，直接操作活动对象
//	 * @param planActivityOid
//	 * @return
//	 * @throws WTPropertyVetoException
//	 * @throws WTException
//	 * @author xucr
//	 * @throws JSONException 
//	 * @CreateDate 2020年8月31日
//	 */
//	public JSONObject reject(String params) throws JSONException, WTException {
//		JSONObject obj = new JSONObject(params);
//		String tip = "";
//		if(obj.has("type") && obj.has("planActivityOid")) {
//			String type = obj.getString("type");
//			String planActivityOid = obj.getString("planActivityOid");
//			PlanActivity activity = (PlanActivity) TMUtil.oid2Obj(planActivityOid);
//			if(null != activity) {
//				JSONObject attrs = new JSONObject();
//				if("2".equals(type) ) {//驳回操作：已上载，不达标
//					attrs.put("isUpload", APQPProjectConstant.YES);
//					attrs.put("isStandard", APQPProjectConstant.NO);
//				} else if("1".equals(type)) {//取消驳回操作：已上载，已达标
//					attrs.put("isUpload", APQPProjectConstant.YES);
//					attrs.put("isStandard", APQPProjectConstant.YES);
//				}
//				planactivityservice.setPlanactivitySTDAttr(activity, attrs);
//			} else {
//				tip = APQPProjectConstant.TIP4;
//			}
//		} else {
//			tip = APQPProjectConstant.TIP4 + "!";
//		}
//		
//		JSONObject result = new JSONObject();
//		result.put("msg", tip);
//		result.put("code", StringUtils.isEmpty(tip) ? 0 : 1);
//		return result;
//	}
	
	/**
	 * 资料 : 驳回/取消驳回，记录在表单数据
	 * @param params
	 * @return
	 * @throws JSONException
	 * @throws WTException
	 * @throws WTPropertyVetoException
	 * @author xucr
	 * @CreateDate 2020年9月9日
	 */
	public JSONObject reject(String params) throws JSONException, WTException, WTPropertyVetoException {
		JSONObject obj = new JSONObject(params);
		String tip = "";
		if(obj.has("type") && obj.has("planActivityOid")) {
			String type = obj.getString("type");// type=2,取消驳回，  1，驳回
			String planActivityOid = obj.getString("planActivityOid");
			PlanActivity activity = (PlanActivity) TMUtil.oid2Obj(planActivityOid);
			Project2 project = (Project2) activity.getContainer();
			// 通过项目，找到process
			FormDataXml xml = findFormDataXml(null, project);

			Blob blob = xml.getFormcontent();
			String str = ProjectUtil.blob2str(blob);
			JSONObject _str = new JSONObject(str);
			
			if(APQPProjectConstant.STANDARD_2.equals(type)) {// 驳回操作
				if(_str.has(REJECTOID)) {
					_str.put(REJECTOID, _str.getString(REJECTOID) + APQPProjectConstant.SPLITVALUE + planActivityOid);
				} else {
					_str.put(REJECTOID, planActivityOid);
				}
			} else if(APQPProjectConstant.STANDARD_1.equals(type)) {//取消驳回
				if(_str.has(REJECTOID)) {
					_str.put(REJECTOID, _str.getString(REJECTOID).replace(planActivityOid, ""));
				}
			}
			xml.setFormcontent(ProjectUtil.str2Blob(_str.toString()));
			PersistenceHelper.manager.save(xml);
		} else {
			tip = APQPProjectConstant.TIP4 + "!";
		}
		
		JSONObject result = new JSONObject();
		result.put("msg", tip);
		result.put("code", StringUtils.isEmpty(tip) ? 0 : 1);
		return result;
	}
	
	public void updateDate(WfProcess process) {
		/**
		 * 当存在驳回（表单中记录驳回的诗句）时：
		 * 	流程直接结束，除驳回+驳回的父项状态不变，且驳回的任务要变为不达标，其余全部关闭
		 * 当不存在驳回（表单中无记录驳回的诗句）时
		 *  将所有活动变为已完成，将项目变为已完成
		 * */
		try {
			FormDataXml xml = findFormDataXml(process, null);
			Project2 project = (Project2) xml.getPersistable().getObject();
			Plan plan = (Plan) PlanHelper.service.getPlan(ObjectReference.newObjectReference(project));
			
			List<PlanActivity> allActivitys = ProjectUtil.getAllActivity(plan);//所有活动
			List<PlanActivity> rejestActivitys = new ArrayList<PlanActivity>(); //驳回的活动
			List<PlanActivity> rejestParentActivitys = new ArrayList<PlanActivity>();//驳回活动的直接父项
			
			xml.setStatus(APQPProjectConstant.FORMDATA_STATUS_COMPLETED);
			PersistenceHelper.manager.save(xml);
			
			Blob blob = xml.getFormcontent();
			String str = ProjectUtil.blob2str(blob);
			JSONObject _str = new JSONObject(str);
			if(_str.has(REJECTOID)) {
				String rejectOids = _str.getString(REJECTOID);
				String [] oids = rejectOids.split(APQPProjectConstant.SPLITVALUE);
				
				JSONObject projectBean = new JSONObject();
				projectBean.put("isStandard", APQPProjectConstant.NO);
				
				for(String oid : oids) {
					PlanActivity activity = (PlanActivity) TMUtil.oid2Obj(oid);
					if(null != activity) {
						rejestActivitys.add(activity);
						planactivityservice.setPlanactivitySTDAttr(activity, projectBean);
						
						PlanActivity parentActivity = (PlanActivity) activity.getParentPlannable();
						if(!rejestParentActivitys.contains(parentActivity)) {
							rejestParentActivitys.add(parentActivity);
						}
					}
				}
			}
			
			boolean isCompleteProject = false;
			if(rejestActivitys.size() > 0) {//有驳回
				allActivitys.removeAll(rejestActivitys);
				allActivitys.removeAll(rejestParentActivitys);
			} else {//无驳回
				isCompleteProject = true;
			}
			
			//先关闭活动
			if(null != allActivitys && allActivitys.size() > 0) {
				updatePlanActivity(allActivitys);
			}
			
			//再关闭项目
			if(isCompleteProject) {
				completeProject(project);
			}
		} catch (WTException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		} catch (WTPropertyVetoException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 完成活动
	 * @param activityList
	 * @throws Exception
	 * @author xucr
	 * @CreateDate 2020年9月9日
	 */
	public boolean updatePlanActivity(List<PlanActivity> activityList) {
		WTCollection wtCollection = new WTHashSet();
		boolean isTrue = false;
		try {
			for (PlanActivity planActivity : activityList) {
				if(!PlannableState.COMPLETED.equals(planActivity.getPlannableState())) {
					planActivity.setPlannableState(PlannableState.COMPLETED);
					planActivity.setActualFinishDate(new Timestamp(System.currentTimeMillis()));
					wtCollection.add(planActivity);
				}
			}
			PersistenceHelper.manager.save(wtCollection);
			isTrue = true;
		} catch (WTException e) {
			e.printStackTrace();
		} catch (WTPropertyVetoException e) {
			e.printStackTrace();
		}
		return isTrue;
	}
	
	/**
	 * 完成项目
	 * @param activityList
	 * @throws Exception
	 * @author xucr
	 * @CreateDate 2020年9月10日
	 */
	public void completeProject(Project2 project) {
		if(null != project) {
			try {
				ContainerTeamManagedInfo ctinfo = project.getContainerTeamManagedInfo();
				ctinfo.setState(ContainerTeamManagedState.COMPLETED);
				
				Date endDate = new Date();
				ctinfo.setActualEnd(new Timestamp(endDate.getTime()));
				project.setContainerTeamManagedInfo(ctinfo);
				
				PersistenceHelper.manager.save(project);
				PersistenceHelper.manager.refresh(project);
			} catch (WTException e) {
				e.printStackTrace();
			} catch (WTPropertyVetoException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 直接关闭任务、项目
	 * @param project
	 * @author xucr
	 * @CreateDate 2020年10月12日
	 */
	public void closedProject(Project2 project) {
		try {
			Plan plan = (Plan) PlanHelper.service.getPlan(ObjectReference.newObjectReference(project));
			List<PlanActivity> allActivitys = ProjectUtil.getAllActivity(plan);//所有活动
			//先关闭活动
			boolean isTrue = false;
			if(null != allActivitys && allActivitys.size() > 0) {
				isTrue = updatePlanActivity(allActivitys);
			}
			//再关闭项目
			if(isTrue) {
				completeProject(project);
			}
		} catch (WTException e) {
			e.printStackTrace();
		}
	}
	
	public static void updateDate(ObjectReference self) {
		/**
		 * 当存在驳回（已上载，不达标）时：
		 * 	流程直接结束，除驳回+驳回的父项外，其余全部关闭
		 * 当不存在驳回（已上载，不达标）时
		 *  将所有活动变为已完成，将项目变为已完成
		 * */
		WfProcess process = BomWorkFlowUtil.getProcess(self);// 获取流程
//		updateDate(process);
	}
	
//	public <E> Object toObject(Blob blob)throws  IOException{
//		
//		Object list = new Object();
//		try  {
//            ObjectInputStream in  = new ObjectInputStream(blob.getBinaryStream());
//            list = in.readObject();
//            in.close();   
//        }  catch  (Exception e) {
//            e.printStackTrace();
//        }
//		return list;
//	}
			
}
